package com.innovatio.validator.handlers;

import com.innovatio.validator.Validable;
import com.innovatio.validator.exceptions.ValidatorException;
import com.innovatio.validator.ValidationErrors;
import com.innovatio.validator.annotations.ValidateEmail;
import com.innovatio.utils.general.CommonsUtils;

import java.util.regex.Pattern;

/**
 * This code is property of Innovatio Software Solutions, Inc.
 * Project PaySmart
 * User: Ramon
 * Date: Mar 4, 2009
 * Time: 11:01:47 AM
 */
public class ValidateEmailHandler implements ValidationHandler<ValidateEmail> {

    private static final String EMAIL_REGEXP = "^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@";
    private static final String EMAIL_DOMAIN_PATTERN = "((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$";

    public ValidationErrors.Error validate(ValidateEmail annotation, Validable container, String fieldName, String value) throws ValidatorException {

        if (CommonsUtils.isStringEmpty(value))
            return null;

        String finalExpresion = EMAIL_REGEXP;

        if (annotation.domain().equals(CommonsUtils.EMPTY)) {
            finalExpresion+= EMAIL_DOMAIN_PATTERN;
        } else
            finalExpresion+= annotation.domain();

        if (!Pattern.matches(finalExpresion, value)) {
            return new ValidationErrors.Error(fieldName, annotation.i18nBundleKey());
        }
        return null;
    }

}